package logic

import (
	"common/model"
	"context"
	"errors"
	"product_server/domain/consts"
	"product_server/product_pkg"
	product "product_server/proto"
	"strconv"
	"strings"
	"time"
)

func (p *ProductServer) ParseTaoBao(ctx context.Context, req *product.ParseTaoBaoRequest) (*product.ParseTaoBaoResponse, error) {
	// 解析token
	if !strings.HasSuffix(req.TaobaoUrl, consts.TOKEN_SUFFIX) || !strings.HasPrefix(req.TaobaoUrl, consts.TOKEN_PERFIX) {
		return nil, errors.New("淘口令错误")
	}
	// 解析token
	encoded := req.TaobaoUrl[len(consts.TOKEN_PERFIX) : len(req.TaobaoUrl)-len(consts.TOKEN_SUFFIX)] // 截取字符串
	tokenData, err := product_pkg.DecodeToken(encoded)                                               // 解析token
	if err != nil {
		return nil, errors.New("淘口令错误")
	}
	// 检查token是否过期
	if time.Now().Unix()-tokenData.Timestamp > 3600 {
		return nil, errors.New("淘口令已过期")
	}

	gb := model.GroupBuy{}

	gid, _ := strconv.Atoi(tokenData.GroupID)
	err = gb.Detail(gid)
	if err != nil {
		return nil, err
	}

	if gb.Id == 0 {
		return nil, errors.New("拼团不存在")
	}

	return &product.ParseTaoBaoResponse{
		GroupId: int64(gb.Id),
	}, err
}
